import type { Ipc } from 'shared-types'

import { contextBridge, ipcRenderer } from 'electron'

type IpcRenderer = typeof ipcRenderer
type IpcRendererEvent = Parameters<Parameters<IpcRenderer['on']>[1]>[0]

// TODO:考虑 ipcRenderer 上的 listeners 的 remove
const ipc: Ipc = {
  // send(channel, ...args) {
  //   ipcRenderer.send(channel, ...args)
  // },
  // on(channel, listener) {
  //   return ipcRenderer.on(channel, listener)
  // },
  off(event, listener) {
    ipcRenderer.off(event, listener)
  },
  sendWinStartLogin(code) {
    ipcRenderer.send('win-start-login', code)
  },
  sendViewStartCreate(url) {
    ipcRenderer.send('view-start-create', url)
  },
  sendViewStartHistoryChange(id, opt) {
    ipcRenderer.send('view-start-history-change', id, opt)
  },
  sendViewActive(id) {
    ipcRenderer.send('view-active', id)
  },
  sendViewRemove(id, nextId) {
    ipcRenderer.send('view-remove', id, nextId)
  },
  onWinDidLogin(listener) {
    ipcRenderer.on('win-did-login', (_event, platforms) => listener(platforms))
  },
  onWinDidLogout(listener) {
    ipcRenderer.on('win-did-logout', listener)
  },
  onViewMainFrameCreated(listener) {
    ipcRenderer.on('view-main-frame-created', (_event, id) => listener(id))
  },
  onViewDidStartLoading(listener) {
    ipcRenderer.on('view-did-start-loading', (_event, id) => listener(id))
  },
  onViewDidStartNavigation(listener) {
    ipcRenderer.on('view-did-start-navigation', (_event, id, url) => listener(id, url))
  },
  onViewDidStopLoading(listener) {
    ipcRenderer.on('view-did-stop-loading', (_event, id, canGoBack, canGoForward) => listener(id, canGoBack, canGoForward))
  },
  onViewPageFaviconUpdated(listener) {
    ipcRenderer.on('view-page-favicon-updated', (_event, id, favicons) => listener(id, favicons))
  },
  onViewPageTitleUpdated(listener) {
    ipcRenderer.on('view-page-title-updated', (_event, id, title) => listener(id, title))
  }
}

contextBridge.exposeInMainWorld('ipc', ipc)
